<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\mongo\MongoOePicModel;
use app\model\OeSourcePicModel;
use app\model\OeSourceUrlModel;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class SourcePicService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['source_pic'];

    /**
     * 拉取数据.
     * @param string $keyStr redis队列信息
     */
    public static function getPicList(string $keyStr = ''): bool
    {
        $key = explode('_', $keyStr);
        if (count($key) < 3) {
            return self::setError('队列信息错误');
        }
        $accountId = intval($key[0]);
        $id = strval($key[1]);
        $type = intval($key[2]);
        Db::startTrans();
        try {
            $data = [];
            $num = 0;
            $schemaUrlId = 0;
            if ($type == 1) {
                $schemaUrlId = $id;
                $schemaUrl = self::getSourceUrl($id);
                if (! $schemaUrl instanceof OeSourceUrlModel || ! $schemaUrl->getKey()) {
                    throw new \Exception('直达链接信息获取失败');
                }
                // 查询匹配的
                $picData = (new MongoOePicModel())->where('account_id', $accountId)->whereLike('filename', $schemaUrl->getAttr('link_name'))->select()->toArray();
                if ($picData) {
                    foreach ($picData as $pic) {
                        $data[] = [
                            'source_id' => $id,
                            'account_id' => $accountId,
                            'material_id' => $pic['material_id'],
                            'pic_type' => $pic['width'] > $pic['height'] ? OceanEnum::CREATIVE_IMAGE_MODE_IMAGE : OceanEnum::CREATIVE_IMAGE_MODE_IMAGE_VERTICAL,
                            'create_time' => time(),
                        ];
                    }
                    $num = count($data);
                }
            } else {
                $pic = (new MongoOePicModel())->where('account_id', $accountId)->where('material_id', $id)->find();
                if ($pic) {
                    $code = explode('_', $pic['filename'])[0];
                    if ($code) {
                        $urlData = (new OeSourceUrlModel())->where('account_id', $accountId)->where('link_name', $code)->find();
                        if ($urlData) {
                            $data[] = [
                                'source_id' => $urlData['id'],
                                'account_id' => $accountId,
                                'material_id' => $pic['material_id'],
                                'pic_type' => $pic['width'] > $pic['height'] ? OceanEnum::CREATIVE_IMAGE_MODE_IMAGE : OceanEnum::CREATIVE_IMAGE_MODE_IMAGE_VERTICAL,
                                'create_time' => time(),
                            ];
                            $num = 1;
                            $schemaUrlId = $urlData['id'];
                        }
                    }
                }
            }
            if (! empty($data)) {
                if (! (new OeSourcePicModel())->insertAll($data)) {
                    throw new \Exception('保存信息出错');
                }
                if ($schemaUrlId) {
                    if (! (new OeSourceUrlModel())->where('id', $schemaUrlId)->inc('pic_num', $num)->update()) {
                        throw new \Exception('修改视频数量出错');
                    }
                }
            }

            if ($type == 1 && ! (new OeSourceUrlModel())->where('id', $schemaUrlId)->update(['is_sync_pic' => 1])) {
                throw new \Exception('修改状态出错');
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取直达链接信息.
     * @param string $id 主键id
     * @return bool|mixed|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getSourceUrl(string $id = '')
    {
        return (new OeSourceUrlModel())->where('id', $id)->find();
    }
}
